package cn.client.ui.view.main.dynamic

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.AddToPhotos
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.PopupProperties
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import cn.client.R
import coil.compose.rememberAsyncImagePainter
import coil.request.ImageRequest


/**
 * 编辑动态页面，用于上传动态
 */
@Composable
fun EditDynamic(
    userId: Int,
    navController: NavController,
    viewModel: DynamicViewModel = hiltViewModel()
) {
    val images = viewModel.images
    val context = LocalContext.current

    var content: String by remember {
        mutableStateOf("")
    }

    val imageResultLauncher = rememberLauncherForActivityResult(
//        contract = ActivityResultContracts.GetContent(),
        contract = ActivityResultContracts.StartActivityForResult()
    ) { result: ActivityResult ->
//        if (uri != null) {
//            viewModel.dispatch(DynamicViewModel.PageIntent.UploadImage(uri))
//        } else {
//            Toast.makeText(context,"上传失败！", Toast.LENGTH_SHORT).show()
//        }
        if (result.resultCode == Activity.RESULT_OK){
            val data: Intent? = result.data
            data?.data?.let { uri ->
                viewModel.dispatch(DynamicViewModel.PageIntent.UploadImage(uri))
            }
        }
    }

    LaunchedEffect(Unit) {
        viewModel.pageEvents.collect { it ->
            when(it) {
                is DynamicViewModel.PageEvent.ImageUploaded -> {
                    Toast.makeText(context,"上传成功！", Toast.LENGTH_SHORT).show()
                }
                is DynamicViewModel.PageEvent.UploadError -> {
                    Toast.makeText(context,"上传失败！", Toast.LENGTH_SHORT).show()
                }
                is DynamicViewModel.PageEvent.Error -> {
                    Toast.makeText(context,"异常：${it.error}", Toast.LENGTH_SHORT).show()
                }
                is DynamicViewModel.PageEvent.Success -> {
                    Toast.makeText(context,"发布成功！", Toast.LENGTH_SHORT).show()
                    navController.navigateUp()
                }
                else -> {}
            }
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.White)
    ) {
        /* 顶部导航栏 */
        EditDynamicTopBar(
            onClickArrowBack = { navController.navigateUp() },
            onClickShareDynamic = {
                viewModel.dispatch(DynamicViewModel.PageIntent.ToShareDynamicReq(
                    DynamicViewModel.ShareDynamicReq(
                    context = context,
                    uid = userId,
                    content = content,
                    category = 0,
                    images = images
                )))
            }
        )
        Spacer(modifier = Modifier
            .fillMaxWidth()
            .height(20.dp))

        /* 内容输入框 */
        Row(
            horizontalArrangement = Arrangement.Center,
            modifier = Modifier
                .fillMaxWidth()
                .wrapContentHeight()
                .padding(5.dp)
        ) {
            TextField(
                value = content,
                onValueChange = { str -> content = str },
                placeholder = { Text(stringResource(R.string.dynamic_edit)) },
                modifier = Modifier
                    .fillMaxWidth()
                    .wrapContentHeight()
                    .padding(5.dp)
            )
        }
        /* 动态视图 */
        UploadDynamicScreen(
            images = images,
            onUploadButton = {
//                imageResultLauncher.launch("image/*") // 启动选择器并选择图片
                val intent = Intent(Intent.ACTION_GET_CONTENT)
                intent.type = "image/*"
                imageResultLauncher.launch(intent)
            }
        )

    }
}



// 顶部导航栏
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun EditDynamicTopBar(
    onClickArrowBack : () -> Unit,
    onClickShareDynamic: () -> Unit
) {
    var expanded by remember { mutableStateOf(false) }
    data class DropdownItem(val title: String, val id: Int)
    val dropdownList = listOf(
        DropdownItem("发布动态", 1))

    TopAppBar(
        colors = TopAppBarDefaults.topAppBarColors(
            containerColor = MaterialTheme.colorScheme.primaryContainer,
            titleContentColor = MaterialTheme.colorScheme.primary
        ),
        title = { Text("编辑动态") },
        /* 左边按钮 */
        navigationIcon = {
            IconButton(onClick = {
                onClickArrowBack()
            }) { Icon(Icons.AutoMirrored.Filled.ArrowBack, null) }
        },
        /* 右边按钮（可以是多个） */
        actions = {
            IconButton(onClick = { expanded =! expanded }
            ) { Icon(Icons.Filled.MoreVert, null) }
            /* 下拉框 */
            DropdownMenu(
                expanded = expanded,
                onDismissRequest = { expanded = !expanded }, // 当下拉菜单展开/关闭时更新状态
                modifier = Modifier.wrapContentSize(),
                properties = PopupProperties(
                    focusable = true,
                    dismissOnBackPress = false,
                    dismissOnClickOutside = true
                )
            ) {
                // 在这里遍历 dropdownList 并创建 DropdownMenuItem
                dropdownList.forEach { dropItem ->
                    DropdownMenuItem(
                        { Text(text = dropItem.title) },
                        onClick = {
                            expanded = false
                            when (dropItem.id) {
                                1 -> {
                                    onClickShareDynamic()
                                }
                                else -> { Unit }
                            }

                        }
                    )
                }
            }
        }
    )
}


// 动态视图
@Composable
fun UploadDynamicScreen(
    images: List<Uri>,
    onUploadButton : () -> Unit,
) {
    Column {
        // 网格布局，三行三列
        LazyVerticalGrid(
            columns = GridCells.Fixed(3),
            modifier = Modifier
                .fillMaxWidth()
                .wrapContentHeight()
                .padding(5.dp)
        ) {
            items(images) { it ->
                ImagePreviewItem(it)
            }
            /* 如果图片数量小于9显示上传组件  */
            if (images.size < 9) {
                item {
                    Box(
                        contentAlignment = Alignment.Center,
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(140.dp)
                            .padding(5.dp)
                            .background(Color.LightGray)
                            .clickable {
                                onUploadButton()
                            }
                    ) {
                        Icon(
                            imageVector = Icons.Default.AddToPhotos,
                            tint = Color.Gray,
                            contentDescription = "Upload Image",
                            modifier = Modifier.size(48.dp)
                        )
                    }
                }
            }
        }
        Row(
            horizontalArrangement = Arrangement.End,
            modifier = Modifier
                .fillMaxWidth()
                .height(50.dp)
                .padding(10.dp)
        ) {
            Text(text = "目前上传${images.size}张图片")
        }
    }
}


// 上传的图片item
@Composable
fun ImagePreviewItem(
    image: Uri
) {
    val painter = rememberAsyncImagePainter(
        ImageRequest.Builder(LocalContext.current)
            .data(data = image)
            .build()
    )

    Box(
        contentAlignment = Alignment.Center,
        modifier = Modifier
            .fillMaxWidth()
            .height(140.dp)
            .clickable {
                /* 处理点击事件，例如预览或删除图片 */

            }
    ) {
        Image(
            painter = painter,
            contentDescription = null,
            contentScale = ContentScale.Crop,
            modifier = Modifier
                .fillMaxSize()
                .padding(5.dp)
        )
    }
}